package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.entity.sync.SyncImportantDaysInfoEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.enums.sync.CrmServiceEnum;
import com.pactera.madp.cp.common.util.sync.SyncUtils;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.mapper.sync.SyncImportantDaysInfoMapper;
import com.pactera.madp.cp.service.sync.SyncImportantDaysInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class SyncImportantDaysInfoServiceImpl extends ServiceImpl<SyncImportantDaysInfoMapper, SyncImportantDaysInfoEntity> implements SyncImportantDaysInfoService {

    private final SyncConfig syncConfig;

    @Override
    public void addYesterdayToHis() {

    }

    @Override
    public void deleteYesterday() {
        log.debug("生日信息：deleteBeforeOneWeek");
        // 只保留7天后到期的数据
        String date = DateUtil.format(new Date(), Constants.DATE_FORMAT);
        String fileDate = SyncStateContext.get().getFileDate();
        if (StrUtil.isNotEmpty(fileDate)) {
            date = fileDate;
        }
        int nowDate = Integer.parseInt(date);

        Date dateTime = new Date();
        if (StrUtil.isNotEmpty(fileDate)) {
            dateTime = DateUtil.parse(date, Constants.DATE_FORMAT);
        }
        int after7Date = Integer.parseInt(DateUtil.format(DateUtil.offsetDay(dateTime, 7), Constants.DATE_FORMAT));
        int nowMonthDay = Integer.parseInt(date.substring(4));
        String yearStr = date.substring(0,4);

        List<String> removeList = new ArrayList<>();

        List<SyncImportantDaysInfoEntity> entityList = this.list();
        entityList.forEach(e -> {
            int year = Integer.parseInt(yearStr);
            int monthday = Integer.parseInt(e.getImportantDt().substring(4));
            int birth = Integer.parseInt(StrUtil.format("{}{}", year, e.getImportantDt().substring(4)));
            // 跨年特殊处理
            if (nowMonthDay >= 1225 && nowMonthDay <= 1231 && monthday >= 101 && monthday <= 107) {
                birth = Integer.parseInt(StrUtil.format("{}{}", year+1, e.getImportantDt().substring(4)));
            }
            // 移除生日不在最近7日内的数据
            if (birth < nowDate || birth > after7Date) {
                removeList.add(e.getTableKey());
            }
        });
        if (!removeList.isEmpty()) {
            this.removeByIds(removeList);
        }
    }

    @Override
    public void parse() {
        log.debug("生日信息：check");
        String fileDate = SyncStateContext.get().getFileDate();
        if (!checkFile(fileDate)) {
            log.info("{}{}", CrmServiceEnum.IMPORTANT_DAYS.getSubType(), "同步文件未生成完毕");
            return;
        }
        log.debug("生日信息：parse");
        String filepath = SyncUtils.buildFilePath(syncConfig.getCrmPath(), Constants.FN_IMPORTANT_DAYS, fileDate);
        File newestFile = SyncUtils.getNewestFile(filepath);

        List<SyncImportantDaysInfoEntity> entityList
                = SyncUtils.parse(newestFile, Constants.SEPARATOR_VERTICAL_LINE, SyncImportantDaysInfoEntity.class, syncConfig.getCrmCharset());

        this.saveBatch(entityList);
    }

    @Override
    public void deleteHisOneDay() {

    }

    @Override
    public void syncBusiness() {
        log.debug("生日信息：syncBusiness");
        SyncStateContext.get().setFinalState(true);
    }

    private boolean checkFile(String fileDate) {
        String filepath = SyncUtils.buildFilePath(syncConfig.getCrmPath(), Constants.FN_IMPORTANT_DAYS_OK, fileDate);
        return SyncUtils.checkFile(filepath);
    }

}
